<?php

namespace app\site\service\site;

use app\common\dict\site\SiteConfigInputTypeDict;
use app\common\exception\AdminApiException;
use app\common\form\ConfigInputField;
use app\common\service\BaseService;
use think\facade\Db;

class SiteConfigService extends BaseService
{


    protected $configGroup = [
        'basics' => '基础配置',
        'mail'   => '邮箱配置',
    ];


    protected $defaultConfig = [];



    public function __construct()
    {
        parent::__construct();
        $this->model = new \app\site\model\SiteConfig();


        $this->defaultConfig = [

            //基础配置
            'basics' => [
                'name' => 'basics',
                'title' => '基础配置',
                'list'  => [
                    (new ConfigInputField('basics','icp','备案号'))
                        ->setTip('域名备案号')
                        ->setType(SiteConfigInputTypeDict::STRING)
                        ->setWeigh(999)
                        ->toArray(),
                    (new ConfigInputField('basics','security','公安备案号'))
                        ->setTip('域名备案号')
                        ->setType(SiteConfigInputTypeDict::STRING)
                        ->setWeigh(998)
                        ->toArray(),
                ]
            ],

            //SMTP邮件配置
            'mail' => [
                'name' => 'mail',
                'title' => '邮件配置',
                'list'  => [
                    (new ConfigInputField('mail','smtp_host','SMTP 服务器'))
                        ->setTip('SMTP 服务器，如：smtp.qq.com')
                        ->setType(SiteConfigInputTypeDict::STRING)
                        ->setWeigh(999)
                        ->toArray(),
                    (new ConfigInputField('mail','smtp_port','SMTP 端口'))
                        ->setTip('SMTP 端口')
                        ->setType(SiteConfigInputTypeDict::NUMBER)
                        ->setWeigh(998)
                        ->toArray(),
                    (new ConfigInputField('mail','smtp_user','SMTP 用户名'))
                        ->setTip('SMTP 用户名')
                        ->setType(SiteConfigInputTypeDict::STRING)
                        ->setWeigh(997)
                        ->toArray(),
                    (new ConfigInputField('mail','smtp_pass','SMTP 密码'))
                        ->setTip('SMTP 密码')
                        ->setType(SiteConfigInputTypeDict::PASSWORD)
                        ->setWeigh(996)
                        ->toArray(),
                    (new ConfigInputField('mail','smtp_verification','SMTP 验证方式'))
                        ->setTip('SMTP 验证方式')
                        ->setType(SiteConfigInputTypeDict::SELECT)
                        ->setWeigh(995)
                        ->setContent(['SSL' => 'SSL', 'TLS' => 'TLS'])
                        ->toArray(),
                    (new ConfigInputField('mail','smtp_from','发件人'))
                        ->setTip('发件人')
                        ->setType(SiteConfigInputTypeDict::STRING)
                        ->setWeigh(994)
                        ->toArray()
                ]
            ],

            // 其他分组配置


        ];

    }


    /**
     * 初始化配置，每次新增配置后，需要再次调用此方法
     * @param $site_id
     * @return bool
     */
    public function init($site_id)
    {
        //初始化数据库配置
        $ret = false;
        foreach ($this->defaultConfig as &$group_config){
            foreach ($group_config['list'] as &$config){
                if($this->count(['site_id' => $site_id, 'name' => $config['name']]) <= 0){
                    $config['site_id'] = $site_id;

                    foreach ($config as $field => &$value){
                        if(is_array($value)) $value = json_encode($value);
                    }
                    unset($config['var_name']);
                    $ret = Db::name('config')->insert($config);
                }

            }
        }
        return $ret;
    }




    /**
     * 获取配置分组
     * @return mixed|string[]
     */
    public function getConfigGroup(): mixed
    {
        return $this->configGroup;
    }



    public function getConfig($site_id,string $group = 'all')
    {
        $where = ['site_id' => $site_id];
        if($group != 'all') $where[] = ['group' => $group];

        //根据$where条件查询，按`group`字段分组
        $configs = $this->model->where($where)->order('weigh desc')->select();
        $group_config = [];
        foreach ($configs as $config) {
            $group_config[$config['group']][] = $config;
        }

        foreach ($group_config as $group_name => &$group_list){
            $this->defaultConfig[$group_name]['list'] = $group_list;
        }
        return $this->defaultConfig;
    }


    /**
     * 保存配置，用于前台提交保存
     * @param $site_id
     * @param array $configs
     * @return bool
     */
    public function saveConfig($site_id,array $configs)
    {
        $saveData['site_id'] = $site_id;
        $fields = $this->getAllConfigFields();

        //过滤掉不存在的字段
        foreach ($fields as $field){
            if(array_key_exists($field, $configs)){
                $saveData[$field] = $configs[$field];
            }
        }
        return $this->model->save($saveData);
    }


    /**
     * 获取所有配置字段
     * @return array
     */
    private function getAllConfigFields(): array
    {
        $fields = [];
        foreach ($this->defaultConfig as $group_name => $group_config) {
            foreach ($group_config['list'] as $config) {
                $fields[] = $config['name'];
            }
        }
        return $fields;
    }




}